import sublime, sublime_plugin

import os, shutil, sys, re, getpass, time

# 替换相关文件信息
# @param filePath 目标文件路径，含文件名
# @param oldClassName 旧的类名
# @param newClassName 新的类名
def replaceFileInfo(filePath, oldClassName, newClassName):
	
	if not os.path.isfile(filePath):
		print("文件不存在")
		return

	fr = open(filePath, "r", -1, "utf8")
	content = fr.read()
	fr.close()

	pattern = "{%s}" % oldClassName
	content = re.sub(pattern, newClassName, content)

	user = getpass.getuser()
	content = re.sub("{author}", user, content)

	date = time.strftime('%Y-%m-%d',time.localtime(time.time()));
	content = re.sub("{date}", date, content)

	fw = open(filePath, "w+", -1, "utf8")
	fw.write(content)
	fw.close()

	return

# 创建相关文件
# @param tplName 模板文件名
# @param filePath 目标文件路径
# @param fileName 目标文件名，不包含扩展名
def createFile(view, filePath, fileName, fileType):
	if len(filePath) == 0:
		filePath = view.window().extract_variables().get('folder','')
	
	print(filePath)

	if not filePath or len(filePath) == 0:
		return

	root = sublime.packages_path()

	tplPath = os.path.join(root, "wlgame-plugin", "template")
	print("tplPath: " + tplPath)
	tplFilePath = os.path.join(tplPath, "Template" + fileType + ".lua")

	targetFilePath = os.path.join(filePath, fileName + fileType + ".lua")

	if not os.path.isfile(tplFilePath):
		print("模板文件不存在", tplFilePath)
		return

	if not os.path.exists(filePath):
		print("创建目标文件夹", filePath)
		os.makedirs(filePath)

	if not os.path.exists(targetFilePath):
		shutil.copyfile(tplFilePath, targetFilePath)
		replaceFileInfo(targetFilePath, "Template", fileName)
		view.window().open_file(targetFilePath)
	else:
		print("目标文件已存在")

# 创建part文件命令，暂未用到，可用wlgame_create_file统一接口
class wlgame_create_part_fileCommand(sublime_plugin.TextCommand):

	# run方法
	# @param filePath 文件路径
	# @param fileName 文件名，不含扩展名
	def run(self, edit, filePath, fileName="Template"):

		fileName = fileName.replace("Part", "").replace("part", "")
		def on_done(fileName):
			print(fileName)
			createFile(self.view, "Template", filePath, fileName, "Part")

		def on_change(fileName):
			return

		def on_cancel():
			return 

		self.view.window().show_input_panel("输入文件名", "", on_done, on_change, on_cancel)

# 创建layer文件命令，暂未用到，可用wlgame_create_file统一接口
class wlgame_create_layer_fileCommand(sublime_plugin.TextCommand):

	# run方法
	# @param filePath 文件路径
	# @param fileName 文件名，不含扩展名
	def run(self, edit, filePath, fileName="Template"):

		fileName = fileName.replace("Layer", "").replace("layer", "")
		def on_done(fileName):
			print(fileName)
			createFile(self.view, "Template", filePath, fileName, "Layer")

		def on_change(fileName):
			return

		def on_cancel():
			return 

		self.view.window().show_input_panel("输入文件名", "", on_done, on_change, on_cancel)

# 创建logic文件命令，暂未用到，可用wlgame_create_file统一接口
class wlgame_create_logic_fileCommand(sublime_plugin.TextCommand):

	# run方法
	# @param filePath 文件路径
	# @param fileName 文件名，不含扩展名
	def run(self, edit, filePath, fileName="Template", type=None, paths=[None]):
		
		fileName = fileName.replace("Logic", "").replace("logic", "")
		def on_done(fileName):
			print(fileName)
			createFile(self.view, "Template", filePath, fileName, "Logic")

		def on_change(fileName):
			return

		def on_cancel():
			return 

		self.view.window().show_input_panel("输入文件名", "", on_done, on_change, on_cancel)

# 创建模块命令，暂未用到，可用wlgame_create_file统一接口
class wlgame_create_module_fileCommand(sublime_plugin.TextCommand):

	# run方法
	# @param filePath 文件路径
	# @param moduleName 模块名，不包含part, layer, logic等后缀
	def run(self, edit, filePath, moduleName="Template"):
		# 创建part
		partName = moduleName + "Part"
		createFile(self.view, filePath, partName, "Part")
		# 创建layer
		layerName = moduleName + "Layer"
		createFile(self.view, filePath, layerName, "Layer")
		# 创建logic
		logicName = moduleName + "Logic"
		createFile(self.view, filePath, logicName, "Logic")

# 创建模板文件统一接口
class wlgame_create_fileCommand(sublime_plugin.TextCommand):

	# @param fileType 文件类型，分别为：Part、Layer、Logic、Module
	# @param paths 新建文件路径，只有从左侧文件树点击创建时有值
	def run(self, edit, fileType, paths):
		view = self.view

		if not fileType:
			return

		if paths == None or paths == [None]:
			paths[0] = view.window().extract_variables().get('folder','')

		filePath = paths[0]

		def on_done(fileName):
			# 文件名统一首字母大写
			# fileName = fileName.capitalize()
			if fileType == "Module":
				# 模块名称，模块名文件夹名称统一小写
				moduleDirName = fileName.lower() 
				# 创建模块，会同时创建三个模板文件
				createFile(self.view, os.path.join(filePath, moduleDirName), fileName, "Part")
				createFile(self.view, os.path.join(filePath, moduleDirName), fileName, "Layer")
				createFile(self.view, os.path.join(filePath, moduleDirName), fileName, "Logic")
			else:
				# tplName = "Template" + fileType
				# if not fileName.endswith(fileType):
				# 	fileName = fileName + fileType
				fileName = fileName.replace(fileType, "").replace(fileType.lower(), "")
				# 创建对应模板文件
				createFile(self.view, filePath, fileName, fileType)

		def on_change(fileName):
			return

		def on_cancel():
			return 

		tips = "请输入文件名："
		if fileType == "Module":
			tips = "请输入模块名称："
		else:
			tips = "请输入%s文件名：" % fileType

		view.window().show_input_panel(tips, "", on_done, on_change, on_cancel)	


